import React, { useState, useImperativeHandle } from 'react';
import './addCreateActivity.less';
import {
  Form,
  Input,
  Cascader,
  DatePicker,
  Upload,
  Button,
  Space,
  Collapse,
  Select,
} from 'antd';
import {
  LoadingOutlined,
  PlusOutlined,
  MinusCircleOutlined,
  CloseCircleOutlined,
  CaretRightOutlined,
  CaretUpOutlined,
} from '@ant-design/icons';
function VoteActive(props, ref) {
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const { Panel } = Collapse; //2
  const [imageUrl1, setImageUrl1] = useState([]);
  //   const [loading1, setLoding1] = useState(false);
  //保证至少有一个选项没有隐藏才能提交
  const [voteWay, setVoteWay] = useState(false);
  const [voteForm] = Form.useForm();
  const moment = require('moment');

  useImperativeHandle(ref, () => {
    return {
      nextChoose() {
        let y = props.allData.filter((item) => {
          return item.activityType == 2;
        })[0];
        // console.log(y);
        if (y) {
          if (y.voteWay == 2) {
            setVoteWay(true);
          }
          // console.log(y?.voteObjectVOS);
          let p = y?.voteObjectVOS.map((item) => ({
            pollItemName: item.name,
            pollExplain: item.instructions,
            pollimg: [
              {
                uid: -1,
                pictureKey: item.pictureKey,
                pictureUrl: item.pictureUrl,
              },
            ],
          }));
          let l = p.map((item) => item.pollimg[0].pictureUrl);
          setImageUrl1(l);
          console.log('===============', l);
          voteForm.setFieldsValue({
            voteActivityTime: [moment(y?.startDate), moment(y?.endDate)],
            voteWay: y?.voteWay,
            voteOneName: y?.dayVoteLimit,
            voteMoreName: y?.singlePlayerLimit,
            pollObj: p,
          });
        }
      },
      sonsClick() {
        voteForm.validateFields().then(() => {
          // console.log(voteForm.getFieldValue().pollObj);
          let y = voteForm.getFieldValue().pollObj?.map((item) => ({
            name: item.pollItemName,
            instructions: item.pollExplain,
            pictureKey: item.pollimg[0].response.data.imgKey,
            pictureUrl: item.pollimg[0].response.data.imgUrl,
          }));
          // console.log(y);
          let startDate = moment(
            voteForm?.getFieldValue()?.voteActivityTime[0],
          ).format('YYYY-MM-DD HH:mm');
          let endDate = moment(
            voteForm?.getFieldValue()?.voteActivityTime[1],
          ).format('YYYY-MM-DD HH:mm');
          let g = {};
          g.activityType = 2;
          g.startDate = startDate;
          g.endDate = endDate;
          g.voteWay = +voteForm.getFieldValue().voteWay;
          if (voteForm.getFieldValue().voteWay == 2) {
            g.dayVoteLimit = voteForm.getFieldValue().voteOneName;
            g.singlePlayerLimit = voteForm.getFieldValue().voteMoreName;
          }
          g.voteObjectVOS = y;
          // console.log(g);
          return g;
          // props.upmClick(g);
        });
      },
    };
  });

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  function expandIcon(panelProps) {
    if (panelProps.isActive) {
      return (
        <div>
          收起
          <CaretUpOutlined />
        </div>
      );
    } else {
      return (
        <div>
          展开
          <CaretRightOutlined />
        </div>
      );
    }
  }
  const normFile = (e) => {
    //如果是typescript, 那么参数写成 e: any
    // console.log('Upload event:', e.fileList[0]);
    // if (e.fileList[0]?.response?.code == 200) {
    //   // console.log('1541564654566666666');
    //   setImageData(e.fileList[0]?.response?.data);
    // }
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  const handleChange1 = (info) => {
    // if (info.file.status === 'uploading') {
    //   // this.setState({ loading: true });
    //   setLoding1(true);
    //   return;
    // }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl) => {
        let f = [...imageUrl1];
        f.push(imageUrl);
        setImageUrl1(f);
        console.log(f);
      });
    }
  };
  function voteChange(e) {
    console.log(e);
    if (e == 1) {
      setVoteWay(false);
    } else {
      setVoteWay(true);
    }
  }
  return (
    <div>
      <Collapse expandIconPosition="right" expandIcon={expandIcon}>
        <Panel key="1" header="投票">
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              marginBottom: '20px',
            }}
          >
            <div className="title-icos"></div>
            <div className="title-name">基本信息</div>
          </div>
          <Form name="vote" form={voteForm}>
            <div className={voteWay ? 'title-box1' : 'title-box2'}>
              <div
                style={{
                  display: 'flex',
                  marginTop: '20px',
                }}
              >
                <Form.Item
                  name="voteActivityTime"
                  label="活动时间"
                  rules={[
                    {
                      required: true,
                      message: '请输入活动时间',
                    },
                  ]}
                >
                  <RangePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    style={{ width: '400px', marginRight: '300px' }}
                  />
                </Form.Item>
                <Form.Item label="投票方式" name="voteWay">
                  {/* <Input style={{ width: '400px' }} placeholder="只可投一次" /> */}
                  <Select
                    placeholder="Please select"
                    onChange={voteChange}
                    style={{ width: '400px' }}
                  >
                    <Option value={1}>只投一次</Option>
                    <Option value={2}>每日均可投</Option>
                  </Select>
                </Form.Item>
              </div>

              <div className={voteWay ? 'vote-all' : 'vote-play'}>
                <Form.Item label="单日可投上限" name="voteOneName">
                  <Input
                    style={{ width: '400px', marginRight: '255px' }}
                    placeholder=""
                  />
                </Form.Item>
                <Form.Item label="重复可投上限" name="voteMoreName">
                  <Input style={{ width: '400px' }} placeholder="" />
                </Form.Item>
              </div>
            </div>

            <div
              style={{
                border: '1px solid #efeff2',
                padding: '10px 20px 30px',
                marginTop: '15px',
                marginBottom: '15px',
              }}
            >
              <Form.List name="pollObj">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }, index) => (
                      <Space
                        key={key}
                        align="baseline"
                        style={{
                          display: 'flex',
                          flexDirection: 'column',
                          width: '100%',
                        }}
                      >
                        <div
                          style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            width: '100%',
                          }}
                        >
                          <Form.Item
                            {...restField}
                            label="名称"
                            name={[name, 'pollItemName']}
                            rules={[
                              {
                                required: true,
                                message: '请输入项目名称',
                              },
                            ]}
                          >
                            <Input placeholder="请输入投票对象的名称" />
                          </Form.Item>

                          <Form.Item
                            {...restField}
                            label="说明"
                            name={[name, 'pollExplain']}
                            rules={[
                              {
                                required: true,
                                message: '请输入投票说明',
                              },
                            ]}
                          >
                            <Input placeholder="请输入投票对象的说明" />
                          </Form.Item>
                        </div>

                        <div
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                          }}
                        >
                          <Form.Item
                            {...restField}
                            label="图片"
                            valuePropName="fileList"
                            getValueFromEvent={normFile}
                            name={[name, 'pollimg']}
                            rules={[{ required: true, message: '请上传图片' }]}
                          >
                            <Upload
                              name="multipartFile"
                              listType="picture-card"
                              className="avatar-uploader"
                              showUploadList={false}
                              action="/campus/campusweb/upload/pictureUpload"
                              onChange={handleChange1}
                            >
                              {imageUrl1[index] ? (
                                <img
                                  src={imageUrl1[index]}
                                  alt="avatar"
                                  style={{ width: '100%' }}
                                />
                              ) : (
                                <div>
                                  <PlusOutlined />
                                  <div style={{ marginTop: 8 }}>Upload</div>
                                </div>
                              )}
                            </Upload>
                          </Form.Item>
                        </div>
                      </Space>
                    ))}
                    <Form.Item>
                      <Button
                        type="dashed"
                        onClick={() => add()}
                        block
                        icon={<PlusOutlined />}
                      >
                        添加
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </div>
          </Form>
        </Panel>
      </Collapse>
    </div>
  );
}
export default React.forwardRef(VoteActive);
